package com.hqyj.javaSpringCloudAccount.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hqyj.entity.account.Role;
import com.hqyj.entity.common.Result;
import com.hqyj.entity.common.SearchBean;
import com.hqyj.javaSpringCloudAccount.dao.RoleDao;
import com.hqyj.javaSpringCloudAccount.dao.RoleResourceDao;
import com.hqyj.javaSpringCloudAccount.dao.UserRoleDao;
import com.hqyj.javaSpringCloudAccount.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private UserRoleDao userRoleDao;

    @Autowired
    private RoleResourceDao roleResourceDao;

    @Override
    public PageInfo<Role> getRolesBySearchBean(SearchBean searchBean) {
        // 初始化分页列表
        searchBean.initSearchBean();

        // 开始分页
        PageHelper.startPage(searchBean.getCurrentPage(),searchBean.getPageSize());
        return new PageInfo<Role>(Optional
                .ofNullable(roleDao.getRolesByVo(searchBean))
                .orElse(Collections.emptyList()));
    }

    @Override
    public Role getRoleById(int id) {
        return roleDao.getRoleById(id);
    }

    @Override
    public List<Role> getRoles() {
        return roleDao.getRoles();
    }

    @Override
    @Transactional
    public Result<Role> insertRole(Role role) {
        // 因使用的MyBatis，需手动生成时间
        role.setCreateDate(LocalDateTime.now());
        roleDao.insertRole(role);
        return new Result<Role>(Result.ResultCode.SUCCESS.code, "Insert Success.", role);
    }

    @Override
    @Transactional
    public Result<Role> updateRole(Role role) {
        roleDao.updateRole(role);
        return new Result<Role>(Result.ResultCode.SUCCESS.code, "Update Success.", role);
    }

    @Override
    @Transactional
    public Result<Object> deleteRoleById(int id) {
        roleDao.deleteRoleById(id);
        userRoleDao.deleteUserRoleByRoleId(id);
        roleResourceDao.deleteRoleResourceByRoleId(id);
        return new Result<Object>(Result.ResultCode.SUCCESS.code, "Delete Success.");
    }

    @Override
    public List<Role> getRolesByUserId(Integer id) {
        return roleDao.getRolesByUserId(id);
    }
}
